package com.edgclub.edg.fragment;

import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ToggleButton;

import com.edgclub.edg.Constant;
import com.edgclub.edg.R;
import com.edgclub.edg.activity.GzSearchUserActivity;
import com.edgclub.edg.activity.GzTopicSendActivity;
import com.edgclub.edg.activity.MineActivity;
import com.edgclub.edg.event.BroadCastEvent;
import com.edgclub.edg.event.EventBus;
import com.edgclub.edg.model.User;
import com.edgclub.edg.utils.GlideUtil.GlideUtils;
import com.edgclub.edg.utils.util.DensityUtils;
import com.edgclub.edg.utils.util.UserPrefUtils;
import com.squareup.otto.Subscribe;
import com.squareup.otto.ThreadEnforcer;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.HashMap;


public class BBHomeFragment extends GzBaseFragment implements View.OnClickListener {
    private String classname = "BBHomeFragment";
    private ViewPager mViewPager;
    private ArrayList<Fragment> fragmentList;

    private ToggleButton btn_switch;
    private ImageView btn_refresh,btn_write,switch_amin , mine , search;

    private BBChannelFragment btFragment;
    private GlideUtils glideUtils = new GlideUtils();;
    private User user;
    private Activity mActivity;
    private UserPrefUtils userPrefUtils;
    private ObjectAnimator mProgressAnimator;

    public static BBHomeFragment newInstance(String text) {
        BBHomeFragment f = new BBHomeFragment();
        return f;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mActivity = getActivity();
        return inflater.inflate(R.layout.fragment_bb_home, container, false);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON,
                ThreadEnforcer.MAIN).register(this);

    }


    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
    }

    public void initView(View view) {
        userPrefUtils = new UserPrefUtils(getActivity());
        user=userPrefUtils.getUser();
        btn_switch = (ToggleButton) view.findViewById(R.id.btn_switch);
        btn_refresh = (ImageView) getView().findViewById(R.id.btn_refresh);
        btn_write = (ImageView) getView().findViewById(R.id.btn_write);
        mine = (ImageView) getView().findViewById(R.id.mine);
        search = (ImageView) getView().findViewById(R.id.search);
        if(null==user)user=new User();
        glideUtils.Glidde_loadCropCircleImage(getActivity(),userPrefUtils.getUser().getLogo(),mine);
        btn_refresh.setOnClickListener(this);
        btn_write.setOnClickListener(this);
        mine.setOnClickListener(this);
        search.setOnClickListener(this);

        userPrefUtils = new UserPrefUtils(getActivity());
        switch_amin = (ImageView) getView().findViewById(R.id.switch_amin);
        if("0".equals(userPrefUtils.getUser().getUserAuth().getType())){
            btn_write.setVisibility(View.GONE);
        }else {
            btn_write.setVisibility(View.VISIBLE);
        }
        mViewPager = (ViewPager) getView().findViewById(R.id.viewpager_bb);
        fragmentList = new ArrayList<Fragment>();
        btFragment = new BBChannelFragment();
        Fragment secondFragment = GroupListFragment.newInstance("");
        fragmentList.add(btFragment);
        fragmentList.add(secondFragment);
        //给ViewPager设置适配器
        mViewPager.setAdapter(new MyFragmentPagerAdapter(this.getChildFragmentManager(), fragmentList));
        mViewPager.setCurrentItem(0);//设置当前显示标签页为第一页
        mViewPager.setOnPageChangeListener(new MyOnPageChangeListener());//页面变化时的监听器

        btn_switch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });
        btn_switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if(b){
                    mViewPager.setCurrentItem(1);
                }else{
                    mViewPager.setCurrentItem(0);
                }
            }
        });

    }



    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_refresh:
                HashMap<String, Object> hashMap = new HashMap<String, Object>();
                hashMap.put("event", BroadCastEvent.BB_REFRESH);
                hashMap.put("channelId","channelList.get(position).getChannelId()");
                EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON,
                        ThreadEnforcer.MAIN).post(hashMap);
                break;
            case R.id.btn_write:
                Intent intent = new Intent(mActivity, GzTopicSendActivity.class);
                mActivity.startActivity(intent);
                break;
            case R.id.mine:
                Intent intent3 = new Intent(getActivity(), MineActivity.class);
                startActivityForResult(intent3, Constant.USER_RESULT_ICON);
                MobclickAgent.onEvent(getActivity(), "EC_CLICK_MINE");
                break;
            case R.id.search:
                Intent intent4 = new Intent(getActivity(), GzSearchUserActivity.class);
                startActivity(intent4);
//                MobclickAgent.onEvent(getActivity(),"EC_CLICK_MINE");
                break;
        }
    }

    public class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
            // TODO Auto-generated method stub
            setAmian(arg2);


        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onPageSelected(int page) {

            // TODO Auto-generated method stub
            switch (page) {
                case 0:
                    btn_switch.setChecked(false);
                    btn_refresh.setVisibility(View.VISIBLE);
                    btn_write.setVisibility(View.VISIBLE);
                    break;
                case 1:
                    btn_switch.setChecked(true);
                    btn_refresh.setVisibility(View.GONE);
                    btn_write.setVisibility(View.GONE);
                    break;
            }
        }
    }

    private float endx=-0.0f;

    /**
     * 动画
     * @param x_line
     */
    private void setAmian(int x_line){
        if(x_line==0)return;
        float[] arrayOfFloat = new float[2];
        float x_end =0.0f+x_line*90.0f/DensityUtils.getScreenW(getActivity());
        arrayOfFloat[0] =endx;
        arrayOfFloat[1] = (x_end + endx);
        if(arrayOfFloat[1]>90.0){
            arrayOfFloat[1]=90.0f;
        }
        this.mProgressAnimator = ObjectAnimator.ofFloat(switch_amin, "rotation", arrayOfFloat).setDuration(0);
        this.mProgressAnimator.setRepeatCount(-1);
        this.mProgressAnimator.setInterpolator(new LinearInterpolator());
        mProgressAnimator.start();
        endx=x_end;
    }

    class MyFragmentPagerAdapter extends FragmentPagerAdapter {
        ArrayList<Fragment> list;

        public MyFragmentPagerAdapter(FragmentManager fm, ArrayList<Fragment> list) {
            super(fm);
            this.list = list;
        }

        @Override
        public Fragment getItem(int position) {
            return list.get(position);
        }

        @Override
        public int getCount() {
            return list.size();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (btFragment != null) {
            btFragment.onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON,
                ThreadEnforcer.MAIN).unregister(this);
    }

    // 更新用户头像
    @Subscribe
    public void updateUserIocnEvent(HashMap<String, Object> map) {
        String event = (String) map.get("event");
        if (BroadCastEvent.USERICONUPLOAD.equals(event)) {
            User user = (User) map.get("user");
            glideUtils.Glidde_loadCropCircleImage(getActivity(),user.getLogo(),mine);
        }
    }


}

